window.onload = function(){
	
	var api = 'http://h6.duchengjiu.top/shop/';
	
	var userName = document.getElementById('username');
	var passWord = document.getElementById('password');
	var nameMsg = document.getElementById('name-msg');
	var psdMsg = document.getElementById('psd-msg');
	var registerBtn = document.getElementById('register');
	//一开始把注册按钮禁用
	registerBtn.disabled = true;
	//来两把锁
	var lock01 = false;
	var lock02 = false;
	
	//失去焦点的时候要做的事情
	userName.onblur = function(){
		var userNameV = userName.value;
		//console.log(userNameV)
		var re = /^[A-Za-z0-9_]{3,20}$/g;
		//console.log(re.test(userNameV));
		//判断正则
		if(!re.test(userNameV)){
			//用户名不合法
			nameMsg.innerHTML = '用户名不可用';
			nameMsg.style.color= 'red';
			//禁用注册按钮
			registerBtn.disabled = true;
			lock01 = false;
		}else{
			//用户输入的虽然合法，但是这个名字有没有被占用?
			$.post(api + 'api_user.php', {'status':'check', 'username':userNameV}, function(result){
				console.log(result);
				//判断状态
				if(result.code == 0){
					nameMsg.innerHTML = '用户名可用';
					nameMsg.style.color= 'green';
					//放开注册按钮
					lock01 = true;
					if(lock01 && lock02){
						registerBtn.disabled = false;
					};
					
				}else{
					nameMsg.innerHTML = '用户名已存在';
					nameMsg.style.color= 'red';
				};
			})
		}
	};
	
	//密码失去焦点查看合法？
	passWord.onkeyup = function(){
		var passWordV = passWord.value;
		var re = /^[A-Za-z0-9_]{6,20}$/g;
		if(!re.test(passWordV)){
			psdMsg.innerHTML = '密码不可用';
			psdMsg.style.color= 'red';
			registerBtn.disabled = true;
			lock02 = false;
		}else{
			//放开注册按钮
			lock02 = true;
			if(lock01 && lock02){
				registerBtn.disabled = false;
			};
			psdMsg.innerHTML = '密码可用';
			psdMsg.style.color= 'green';
		}
	};
	
	//注册
	registerBtn.onclick = function(){
		var userNameV = userName.value;
		var passWordV = passWord.value;
		//请求后台注册
		$.post(api + 'api_user.php', {'status':'register', 'username':userNameV, 'password':passWordV}, function(result){
			console.log(result);
			if(result.code == 0){
				userName.value = '';
				passWord.value = '';
				alert('恭喜你，注册成功！点击确定跳转到登录页');
				location.href = 'denglu-2.html';
			}
		})
	}
	
};
